package theOrbalEra.common.network;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;

import theOrbalEra.common.block.TileEntityOrballFactory;
import theOrbalEra.common.item.OrbalItemOrbment;
import theOrbalEra.common.util.DefultValue;
import theOrbalEra.common.util.idList.PacketId;

import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.network.packet.Packet250CustomPayload;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;

import com.google.common.io.ByteArrayDataInput;

import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.network.PacketDispatcher;

public class PacketSetOpen extends PacketBase{
	public static PacketSetOpen instance=new PacketSetOpen();
	@Override
	void readClient(int id, ByteArrayDataInput data, Object[] extradata) {
	
		
	}

	@Override
	void readServer(int id, ByteArrayDataInput data, Object[] extradata) {
		int x=data.readInt();
		int y=data.readInt();
		int z=data.readInt();
		int[] cao=new int[6];
		for(int i=0;i<6;i++)
			cao[i]=data.readInt();
		EntityPlayer player=(EntityPlayer) extradata[0];
		 World world=FMLCommonHandler.instance().getMinecraftServerInstance().worldServerForDimension(player.dimension);
		 TileEntity tile=world.getBlockTileEntity(x, y, z);
		 if(tile==null)
			 return;
		 TileEntityOrballFactory fac=(TileEntityOrballFactory) tile;
		setOpen(fac, cao);
			
		
	}
	public void setOpen(TileEntityOrballFactory fac,int[] cao) {
		ItemStack orb = fac.OrbalFacCon[0];
		OrbalItemOrbment.setCao(orb, cao);
	}

	public static void setOpen(int x,int y,int z,int[] cao){
		ByteArrayOutputStream bos = new ByteArrayOutputStream(140);
        DataOutputStream dos = new DataOutputStream(bos);

        try
        {
        	dos.writeInt(PacketId.OPEN_CAO);
            dos.writeInt(x);
            dos.writeInt(y);
            dos.writeInt(z);
            for(int i:cao)
            	dos.writeInt(i);
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }

        Packet250CustomPayload pkt = new Packet250CustomPayload();
        pkt.channel = DefultValue.channel;
        pkt.data = bos.toByteArray();
        pkt.length = bos.size();
        pkt.isChunkDataPacket = false;
        PacketDispatcher.sendPacketToServer(pkt);
		
	}

}
